﻿using CommHelper;
using Newtonsoft.Json.Linq;
using NX5Web.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace NX5Web.ApiFilter
{

    /// <summary>
    /// ApiRoute 的摘要说明
    /// </summary>
    public class ApiRoute : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.Write(PostApi(context));
        }

        private string Decrypt(String key, string value)
        { 
            Byte[] toEncryptArray = Convert.FromBase64String(value);
            using (RijndaelManaged rm = new RijndaelManaged())
            {
                rm.Key = Encoding.UTF8.GetBytes(key);
                rm.IV = Encoding.UTF8.GetBytes(key.Substring(0,16));
                rm.Mode = CipherMode.CBC;
                rm.Padding = PaddingMode.PKCS7;
                rm.FeedbackSize = 128;
                ICryptoTransform encryptor = rm.CreateDecryptor(rm.Key, rm.IV);
                Byte[] resultArray = encryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return Encoding.UTF8.GetString(resultArray);
            } 
        } 

        private String PostApi(HttpContext context)
        {
            string url = "";//地址  
            string getUrl = "";
            string postString = "";
            ApiHandle handle = new ApiHandle();

            System.IO.Stream sream = context.Request.InputStream;
            StreamReader sr = new StreamReader(sream);
            string strXML = sr.ReadToEnd();

            //strXML = context.Server.HtmlDecode(strXML);

            String Method = "POST";

             
            Uri virUrl = null;
            try
            {
                virUrl = new Uri(("http://test.html?filxxs=123&" + strXML).Replace("\"",""));
            }
            catch
            {
                throw new Exception("解析异常.");
            }
            Boolean NeedDecrypt = true;
            if (!String.IsNullOrEmpty(context.Request.QueryString["Encrypt"]))
            {
                NeedDecrypt = Boolean.Parse(context.Request.QueryString["Encrypt"]);
            }

            
             
            var collection = HttpUtility.ParseQueryString(virUrl.Query);


            if (NeedDecrypt)
            {
                String ken = collection["ken"].ToString();
                String DecryptString = Decrypt(ken, collection["encData"].ToString())
                    .Replace("#", "%23");
                try
                {
                    virUrl = new Uri("http://test.html?filxxs=123&" + DecryptString);
                    collection = HttpUtility.ParseQueryString(virUrl.Query);
                }
                catch
                {
                    throw new Exception("解析异常.");
                }   
            }

            JObject jsonObject = new JObject();

            jsonObject["OpUid"] = context.Request.QueryString["OU"];

            // 将查询参数添加到JObject中
            foreach (string key in collection.Keys)
            {
                if (key.ToLower() == "apiurl")
                {
                    if (!collection[key].StartsWith("http"))
                    {
                        url = ConfigManager.GetAppSettings("ApiUrl") + collection[key];
                    }
                    else
                    {
                        url = collection[key];
                    }
                }
                else if (key.ToLower() == "method")
                {
                    Method = collection[key];
                    url = collection["apiurl"];
                }
                else
                {  
                    jsonObject[key] = collection[key];
                }    
            }

            // 序列化JObject为JSON字符串
            string jsonString = jsonObject.ToString().Replace(Environment.NewLine, "");


            //foreach (String key in collection.AllKeys)
            //{
            //    if (String.IsNullOrEmpty(key))
            //    {
            //        continue;
            //    }
            //    if (key.ToLower() == "apiurl")
            //    {
            //        if (!collection[key].StartsWith("http"))
            //        {
            //            url = ConfigManager.GetAppSettings("ApiUrl") + collection[key];
            //        }
            //        else
            //        {
            //            url = collection[key];
            //        }
            //        //url = collection[key];
            //    }
            //    else if (key.ToLower() == "method")
            //    {
            //        Method = collection[key];
            //        url = collection["apiurl"];
            //    }
            //    else
            //    {
            //        if (key.ToLower() == "action")
            //        {
            //            handle.Action = collection[key];
            //        }
            //        if (key.ToLower() == "ken")
            //        {
            //            handle.Key = collection[key];
            //        }
            //        //handle.Parms.Add(key, collection[key]); 
            //        getUrl += key + "=" + collection[key] + "&";
            //        if (Boolean.Parse(context.Request.QueryString["list"]))
            //        {
            //            if ((collection[key].StartsWith("[") && collection[key].EndsWith("]"))
            //                || (collection[key].StartsWith("{") && collection[key].EndsWith("}")))
            //            {
            //                postString += "\"" + key + "\":" + collection[key].Replace("%23", "#") + ",";
            //            }
            //            else
            //            {
            //                postString += "\"" + key + "\":\"" + collection[key].Replace("%23", "#") + "\",";
            //            }
            //        }
            //        else
            //        {

            //            postString += "\"" + key + "\":\"" + collection[key].Replace("%23", "#") + "\",";
            //        }
            //    }
            //}

            //String Setting = "\"OpUid\":" + context.Request.QueryString["OU"];

            //postString = "{" + postString + Setting + "}";

            if (url == "")
            {
                throw new Exception("需要apiurl参数.");
            }
            url = url.Replace("///", "/");

            if(url.IndexOf ("/Encrypt/GetKey") == -1)
            {
                postString = context.Server.UrlEncode(jsonString);
            } 

            //postString = "{\"AuthorId\":\"ff\",\"Name\":\"CaptialInfo\",\"ID\":\"1\",\"Parameters\":[{}]}";

            byte[] postData = Encoding.UTF8.GetBytes(HttpContext.Current.Server.UrlDecode(postString));//编码，尤其是汉字，事先要看下抓取网页的编码方式  

            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/json;charset=UTF-8");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可   
            byte[] responseData = null;
            try
            {
                if (Method.ToLower() == "get")
                {
                    if (getUrl.Length > 0)
                    {
                        getUrl = getUrl.Substring(0, getUrl.Length - 1);
                    }
                    if (url.IndexOf('?') != -1)
                    {
                        getUrl = "&" + getUrl;
                    }
                    else
                    {
                        getUrl = "?" + getUrl;
                    }
                    String trUrl = ConfigManager.GetAppSettings("ApiUrl") + url + getUrl;
                    responseData = webClient.DownloadData(trUrl);
                }
                else
                {
                    responseData = webClient.UploadData(url, "POST",
                        postData);//得到返回字符流   
                }
            }
            catch (Exception e)
            {
                throw new Exception("重新登录" + "[{\"ErrorApi\":\"" + url + "\",\"ErrorApiParas\":\"" + postString + "\",\"msg\":\"" + e.Message + "\"}]");
            }
            string srcString = Encoding.UTF8.GetString(responseData);//解码    

            return srcString;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}